/**
 * Created by sun on 2017/3/28.
 */
define(function (require) {
    var app = require('/../js/app');
    require('ui-table');

    var toastr = require('toastr');

    app.useModule("ui.table");


    var datepicker = require('datepicker');
    app.controller('packMan_planCtrl', ['$scope', '$http', '$filter', function ($scope, $http, $filter) {
        $scope.ctrlScope = $scope;
        datepicker($scope);
        $scope.splitPack = {};

        $scope.select2Options = {
            minimumResultsForSearch: Infinity //不出现搜索框
        };
        $scope.selectOptions = {
            allowClear: false,
            language: 'zh-CN'
        };

        //包列表
        $scope.orderParams = {
            url: "/admin/asset/getPackageList",
            ajax: {status: 2}
        };
        //全局查询
        $scope.search = function () {
            $scope.ctrlScope.itemsearch.beginDateTime = $scope.ctrlScope.itemsearch.beginDateTimex;
            $scope.ctrlScope.itemsearch.endDateTime = $scope.ctrlScope.itemsearch.endDateTimex;
            $scope.ctrlScope.itemsearch.beginDateTime = $filter('date')($scope.ctrlScope.itemsearch.beginDateTime, 'yyyy-MM-dd');
            $scope.ctrlScope.itemsearch.endDateTime = $filter('date')($scope.ctrlScope.itemsearch.endDateTime, 'yyyy-MM-dd');
            //表格查询参数设置
            $scope.orderParams.ajaxParam = $scope.ctrlScope.itemsearch;
            //表格刷新
            $scope.orderParams.reload();
        };
        //全局查询重置
        $scope.reset = function () {
            $scope.orderParams.ajaxParam = {status: 2};
            $scope.ctrlScope.itemsearch = {};
            $scope.orderParams.reload();
        };

        //打包计划列表
        $scope.orderParams1 = {
            url: "/admin/assetPackage/getPackagePlanList",
        };
        //匹配－包列表
        $scope.modifyModal = function (id) {
            $scope.showPageID=id;
            $scope.showPage = !$scope.showPage;
            $scope.orderParams1.ajaxParam = {assetPackageId: id};
            $scope.orderParams1.reload();
        };

        //匹配－列表
        $scope.matchingModal = function (id) {
            $scope.packagePlanId = id;
            $scope.planList4 = [];//数量相同，购买人不同
            $scope.planList5 = [];//数量不同，列表
            $scope.planList2 = [];//上期列表
            $scope.planList3 = [];//上期列表本期列表
            $scope.checkSubmitFlg = false;//自动匹配，当表单被提交过一次后checkSubmitFlg将变为true,根据判断将无法进行提交。
            $scope.matchingSubmitFlg = false;//自动匹配，当表单被提交过一次后matchingSubmitFlg将变为true,根据判断将无法进行提交。
            $scope.ctrlScope.first = {};
            $scope.ctrlScope.packageId = id;
            $scope.matchingPage = !$scope.matchingPage;
            // $scope.planList = [
            //     {id: 1, itemId: 20078, userId: 1234, investDealAmount: 1,},
            //     {id: 2, itemId: 20078, userId: 1233, investDealAmount: 6,},
            //     {id: 3, itemId: 20078, userId: 1232, investDealAmount: 3,},
            //     {id: 4, itemId: 20078, userId: 1231, investDealAmount: 2,},
            //     {id: 5, itemId: 20078, userId: 1230, investDealAmount: 5,},
            // ]
            // $scope.planList1 = [
            //     {id: 11, userId: 1331, investDealAmount: 3,},
            //     {id: 12, userId: 1332, investDealAmount: 3,},
            //     {id: 13, userId: 1233, investDealAmount: 4,},
            //     {id: 14, userId: 1334, investDealAmount: 7,},
            // ]

            //包计划列表
            $http({
                method: 'POST',
                url: "/admin/assetPackage/listInvestBeforeMatch",
                data: {
                    packagePlanId: id
                }
            }).success(function (data) {
                $scope.planList=data.assetInvestList;
                $scope.planList1=data.packageInvestList;
                // $scope.list=data;
            })

        }

        //删除数组
        $scope.removeByValue = function (arr, val) {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] == val) {
                    arr.splice(i, 1);
                    break;
                }
            }
            console.log(arr);
        };

        //自动匹配
        $scope.submitForm = function () {
            if ($scope.checkSubmitFlg == true) {
                return false; //当表单被提交过一次后checkSubmitFlg将变为true,根据判断将无法进行提交。
            }
            $scope.checkSubmitFlg = true;
            $scope.planList4 = [];//数量相同，购买人不同

            angular.copy($scope.planList, $scope.planList2)//上期列表
            angular.copy($scope.planList1, $scope.planList3)//本期列表
            //提交list
            var _list = [];

            for (var i = 0; i < $scope.planList2.length; i++) {

                for (var j = 0; j < $scope.planList3.length; j++) {
                    if ($scope.planList3[j].investDealAmount == $scope.planList2[i].investDealAmount && $scope.planList3[j].userId != $scope.planList2[i].userId) {
                        //上期
                        var planList2 = {};
                        var beforeList = [];
                        //本期
                        var planList3 = {};
                        var laterList = [];

                        //提交list对象
                        var listObject = {};

                        //自动匹配列表
                        var matching = {};

                        angular.copy($scope.planList3[j], planList3);//拷贝本期
                        angular.copy($scope.planList2[i], planList2);//拷贝上期

                        beforeList.push(planList2);
                        laterList.push(planList3);

                        listObject['beforeList'] = beforeList;
                        listObject['laterList'] = laterList;

                        _list.push(listObject);

                        //已匹配列表
                        angular.copy($scope.planList3[j], matching)
                        matching.beforeUserId = $scope.planList2[i].userId;
                        matching.beforeNumber = $scope.planList2[i].investDealAmount;
                        matching.beforeid = $scope.planList2[i].id;
                        $scope.planList4.push(matching);//页面自动匹配列表

                        //删除已匹配
                        $scope.planList2.splice(i, 1);
                        $scope.planList3.splice(j, 1);
                        i--;
                        j--;
                        break;
                    }
                }
            }
            $scope.matchJson = _list;
            //未匹配列表
            angular.copy($scope.planList2, $scope.planList5)
        };

        //拆分
        $scope.split = function () {
            $scope.splitPack = {};
            $scope.splitPage = !$scope.splitPage;
        }

        //拆分提交
        $scope.splitAdd = function () {
            var splitObject = {};

            angular.copy($scope.planList2[$scope.splitPack.companyName], splitObject);//分割出的对象

            var splitNumber = $scope.planList2[$scope.splitPack.companyName]//分割前的份数

            if ($scope.splitPack.investDealAmount >= splitNumber.investDealAmount) {
                return toastr.error('不可以拆分');
            }

            splitNumber.investDealAmount = splitNumber.investDealAmount - $scope.splitPack.investDealAmount;//分割后的份数

            splitObject.investDealAmount = $scope.splitPack.investDealAmount;//分割出的份数

            $scope.planList2[$scope.splitPack.companyName] = splitNumber;

            $scope.planList2.push(splitObject)//上期列表
            $scope.planList5.push(splitObject)//手动匹配列表

            toastr.success('拆分成功！');
            $scope.splitPack = {};
        }


        //TODO:选择上期购买人
        $scope.beforeChange = function (data, feet) {//data－选中的，feet－第几行
            //选择"请选择"时恢复

            if (data == "-1") {
                $scope.planList5[feet].beforeTotal = 0;//统计选中份数清零
                $scope.planList5[feet].beforeUser = [];//统计选中的购买人先清零
                //恢复选中状态
                for (var l = 0; l < $scope.planList5[feet].beforeData[feet].length; l++) {
                    $scope.planList2[$scope.planList5[feet].beforeData[feet][l]].status = -1
                }
                return;
            }

            //禁止重复选择
            for (var k = 0; k < data.length; k++) {

                if ($scope.planList2[data[k]].status != feet && $scope.planList2[data[k]].status != -1 && $scope.planList2[data[k]].status != undefined) {
                    $scope.planList5[feet]._before = angular.copy($scope.planList5[feet].beforeData);
                    toastr.error('不可重复选');
                    return;
                }
            }

            //禁止选择同一购买人
            //for (var ii = 0; ii < data.length; ii++) {
            //    if ($scope.planList5[feet].laterUser != undefined) {
            //        for (var jj = 0; jj < $scope.planList5[feet].laterUser.length; jj++) {
            //            if ($scope.planList5[feet].laterUser[jj] == $scope.planList2[data[ii]].userId) {
            //                $scope.planList5[feet]._before = angular.copy($scope.planList5[feet].beforeData);
            //                toastr.error('购买人不可选同一人');
            //                return
            //            }
            //        }
            //
            //    }
            //}

            //本期选择2组以上时，上期只可单选
            if($scope.planList5[feet]._later != undefined && $scope.planList5[feet]._later[feet].length>1 && $scope.planList5[feet]._before[feet].length>1){
                $scope.planList5[feet]._before = angular.copy($scope.planList5[feet].beforeData);
                toastr.error('不可与匹配对象同时多选');
                return;
            }


            //上期
            $scope.planList5[feet].beforeTotal = 0;//统计选中份数清零
            $scope.planList5[feet].beforeUser = [];//统计选中的购买人先清零

            //恢复选中状态
            if ($scope.planList5[feet].beforeData) {
                for (var j = 0; j < $scope.planList5[feet].beforeData[feet].length; j++) {
                    $scope.planList2[$scope.planList5[feet].beforeData[feet][j]].status = -1
                }
            }

            //改变选中状态并统计
            for (var i = 0; i < data.length; i++) {
                $scope.planList2[data[i]].status = feet//改变选中状态
                $scope.planList5[feet].beforeTotal = $scope.planList5[feet].beforeTotal + $scope.planList2[data[i]].investDealAmount//统计选中份数
                $scope.planList5[feet].beforeUser.push($scope.planList2[data[i]].userId)//统计选中的购买人
            }

            //改变列表数量
            if (data.length > 1) {

                var _beforeLength = $scope.planList5[feet]._before[feet].length//选中购买人的数量
                var beforeLength = $scope.planList5[feet].beforeData[feet].length//之前选中购买人的数量

                if (_beforeLength > beforeLength) {

                    //恢复删除末行中上期状态
                    if ($scope.planList5[$scope.planList5.length - 1]._before != undefined) {
                        //恢复选中状态
                        for (var l = 0; l < $scope.planList5[$scope.planList5.length - 1]._before[$scope.planList5.length - 1].length; l++) {
                            $scope.planList2[$scope.planList5[$scope.planList5.length - 1]._before[$scope.planList5.length - 1][l]].status = -1
                        }
                    }


                    //恢复删除末行中本期数据状态
                    if ($scope.planList5[$scope.planList5.length - 1]._later != undefined) {
                        //恢复选中状态
                        for (var l = 0; l < $scope.planList5[$scope.planList5.length - 1]._later[$scope.planList5.length - 1].length; l++) {
                            $scope.planList3[$scope.planList5[$scope.planList5.length - 1]._later[$scope.planList5.length - 1][l]].status = -1
                        }
                    }


                    //恢复删除末行中上期数据
                    if ($scope.planList5[$scope.planList5.length - 1]._before != undefined) {

                        if (feet != $scope.planList5.length - 1) {
                            var bfLength=$scope.planList5[$scope.planList5.length - 1]._before[$scope.planList5.length - 1].length//要删除行购买人个数
                            for (var ll = 0; ll < bfLength; ll++) {
                                var _list = angular.copy($scope.planList2[$scope.planList2.length - 1])//取得一个对象
                                $scope.planList5.push(_list)//增加一组数据
                            }

                            $scope.planList5.splice($scope.planList5.length - bfLength-1, 1)//删除本组数据
                            $scope.planList5.splice($scope.planList5.length -1, 1)//删除最后一组数据

                        } else if (feet == $scope.planList5.length - 1) {//删除正在操作行
                            for (var ll = 0; ll < $scope.planList5[feet]._before[feet].length - 1; ll++) {
                                var _list = angular.copy($scope.planList2[$scope.planList2.length - 1])//取得一个对象
                                $scope.planList5.push(_list)//增加一组数据
                            }
                            $scope.planList5.splice(feet, 1)//删除本组数据
                        }
                    } else {//删除无数据行
                        $scope.planList5.splice($scope.planList5.length - 1, 1)//删除一组数据
                    }

                } else if (_beforeLength < beforeLength) {
                    var _list = angular.copy($scope.planList2[$scope.planList2.length - 1])
                    $scope.planList5.push(_list)//增加一组数据
                }
            } else if ($scope.planList5[feet].beforeData != undefined) {//beforeData存在且_before数据小于等于1
                var _beforeLength = $scope.planList5[feet]._before[feet].length//选中购买人的数量
                var beforeLength = $scope.planList5[feet].beforeData[feet].length//之前选中购买人的数量

                if (_beforeLength > beforeLength && _beforeLength > 1) {
                    $scope.planList5.splice($scope.planList5.length - 1, 1)//删除一组数据
                } else if (_beforeLength < beforeLength && _beforeLength > 0) {
                    var _list = angular.copy($scope.planList2[$scope.planList2.length - 1])
                    $scope.planList5.push(_list)//增加一组数据
                }
            }

            //保存选择情况
            if ($scope.planList5[feet]._before != undefined) {
                var beforedata = angular.copy($scope.planList5[feet]._before);
                $scope.planList5[feet].beforeData = beforedata;
            }

        }

        //TODO:选择本期购买人
        $scope.laterChange = function (data, feet) {//data－选中的，feet－第几行
            //选择"请选择"时恢复
            if (data == "-1") {
                $scope.planList5[feet].laterTotal = 0;//统计选中份数清零
                $scope.planList5[feet].laterUser = [];//统计选中的购买人先清零
                //恢复选中状态
                for (var l = 0; l < $scope.planList5[feet].laterData[feet].length; l++) {
                    $scope.planList3[$scope.planList5[feet].laterData[feet][l]].status = -1
                }
                return;
            }
            //禁止重复选择
            for (var k = 0; k < data.length; k++) {
                if ($scope.planList3[data[k]].status != feet && $scope.planList3[data[k]].status != -1 && $scope.planList3[data[k]].status != undefined) {
                    $scope.planList5[feet]._later = angular.copy($scope.planList5[feet].laterData);
                    toastr.error('不可重复选');
                    return
                }
            }
            //禁止选择同一购买人
            //for (var ii = 0; ii < data.length; ii++) {
            //    if ($scope.planList5[feet].beforeUser != undefined) {
            //        for (var jj = 0; jj < $scope.planList5[feet].beforeUser.length; jj++) {
            //            if ($scope.planList5[feet].beforeUser[jj] == $scope.planList3[data[ii]].userId) {
            //                $scope.planList5[feet]._later = angular.copy($scope.planList5[feet].laterData);
            //                toastr.error('购买人不可选同一人');
            //                return
            //            }
            //        }
            //
            //    }
            //}

            //上期选择2组以上时，本期只可单选
            if($scope.planList5[feet]._before != undefined && $scope.planList5[feet]._before[feet].length>1 && $scope.planList5[feet]._later[feet].length>1){
                $scope.planList5[feet]._later = angular.copy($scope.planList5[feet].laterData);
                toastr.error('不可与匹配对象同时多选');
                return;
            }

            //本期
            $scope.planList5[feet].laterTotal = 0;//统计选中份数清零
            $scope.planList5[feet].laterUser = [];//统计选中的购买人先清零

            //恢复选择状态
            if ($scope.planList5[feet].laterData) {
                for (var j = 0; j < $scope.planList5[feet].laterData[feet].length; j++) {
                    $scope.planList3[$scope.planList5[feet].laterData[feet][j]].status = -1
                }
            }
            //改变选中状态并统计
            for (var i = 0; i < data.length; i++) {
                $scope.planList3[data[i]].status = feet//改变选中状态
                $scope.planList5[feet].laterTotal = $scope.planList5[feet].laterTotal + $scope.planList3[data[i]].investDealAmount//统计选中份数
                $scope.planList5[feet].laterUser.push($scope.planList3[data[i]].userId)//统计选中的购买人
            }

            //保存选择情况
            var laterData = angular.copy($scope.planList5[feet]._later);
            $scope.planList5[feet].laterData = laterData;
        }

        //匹配提交
        $scope.matchingAdd = function () {
            for (var i = 0; i < $scope.planList5.length; i++) {

                if($scope.planList5[i].beforeTotal<=0 || $scope.planList5[i].beforeTotal==undefined){
                    toastr.error('上期购买人不能未空，请继续操作。');
                    return;
                }

                if($scope.planList5[i].laterTotal<=0 || $scope.planList5[i].laterTotal==undefined){
                    toastr.error('本期购买人不能为空，请继续操作。');
                    return;
                }

                if(($scope.planList5[i].beforeTotal!=$scope.planList5[i].laterTotal)){
                    toastr.error('未匹配，请继续操作。');
                    return;
                }
                var listObject = {};//提交list对象
                var beforeList = [];//提交上期选中数组
                var laterList = [];//提交本期选中数组
                for (var j = 0; j < $scope.planList5[i]._before[i].length; j++) {
                    //上期
                    var planList2 = {};
                    planList2 = $scope.planList2[$scope.planList5[i]._before[i][j]];
                    beforeList.push(planList2);
                }
                listObject['beforeList'] = beforeList;

                for (var jj = 0; jj < $scope.planList5[i]._later[i].length; jj++) {
                    //本期
                    var planList3 = {};
                    planList3 = $scope.planList3[$scope.planList5[i]._later[i][jj]];
                    laterList.push(planList3);
                }
                listObject['laterList'] = laterList;
                $scope.matchJson.push(listObject);
            }
            if ($scope.matchingSubmitFlg == true) {
                return false; //当表单被提交过一次后matchingSubmitFlg将变为true,根据判断将无法进行提交。
            }
            $scope.matchingSubmitFlg = true;
            var matchJson = JSON.stringify($scope.matchJson)
            console.log(matchJson);
            $http({
                method: 'POST',
                url: "/admin/assetPackage/investMatch",
                data: {
                    packagePlanId: $scope.packagePlanId,
                    matchJson: matchJson,
                }
            }).success(function (data) {
                if (data.result == 'fail') {
                    toastr.error('提交失败');
                } else if(data.result == 'success'){
                    toastr.success('提交成功！');
                }
                $scope.matchingPage = !$scope.matchingPage;
            })
        }


        //复审
        $scope.reviewModal = function (id) {
            $scope.reviewPage = !$scope.reviewPage;
            $scope.assetsPackagePlanId = id;
        }

        //复审
        $scope.reviewAdd = function (fullVerifyStatus) {
            $http({
                method: 'POST',
                url: "/admin/asset/packageFullCheck",
                data: {
                    assetsPackagePlanId: $scope.assetsPackagePlanId,
                    fullVerifyStatus: fullVerifyStatus,
                }
            }).success(function (data) {
                if (data.result == 'success') {
                    toastr.success('复审成功！');
                    $scope.orderParams.reload();
                    $scope.orderParams1.reload();
                } else {
                    toastr.error(data.messageText)
                }
                $scope.reviewPage = !$scope.reviewPage;
            })

        };

        //发布
        $scope.releaseModal=function(id){
            $scope.releaseId=id;
            $scope.releasePage=!$scope.releasePage;
        };
        //发布提交
        $scope.releaseSubmit=function(){
            $http({
                method: 'POST',
                url: "/admin/asset/releasePlan",
                data: {packagePlanId:$scope.releaseId}
            }).success(function(data) {
                console.log(data);
                if(data.result=='fail'){
                    if(data.messageText){
                        toastr.error(data.messageText)
                    }else{
                        toastr.error('发布失败')
                    }

                }else{
                    toastr.success('发布成功');
                    $scope.releasePage=!$scope.releasePage;
                    $scope.orderParams1.ajaxParam = {assetPackageId: $scope.showPageID};
                    $scope.orderParams1.reload();
                }
            }).error(function(data) {

            });
        };
        //取消发布
        $scope.cancel=function () {
            $scope.releasePage=!$scope.releasePage;
        };
        //还款
        $scope.repayBtn = function(itemId,repayType) {
            var parm = {
                "packagePlanId": itemId
            };
            var url='';
            if(repayType==1){
                url='/admin/asset/packageRepay';
            }else if(repayType==2){
                url='/admin/asset/brrowerPackageRepay';
            }
            if (confirm("确认还款?")) {
                $http({
                    method: 'POST',
                    url: url,
                    data: parm
                }).success(function(data) {
                    console.log(data);
                    if(data.result=='fail'){
                        if(data.messageText){
                            toastr.error(data.messageText)
                        }else{
                            toastr.error('还款失败')
                        }

                    }else{
                        toastr.success('还款成功');
                        $scope.orderParams1.ajaxParam = {assetPackageId: $scope.showPageID};
                        $scope.orderParams1.reload();
                    }

                }).error(function(data) {});
            } else {
                return
            }
        };

    }]);


});